<?php

/**
 * Validators
 */
define('STANDART_VALIDATOR','service/input/StandartValidator');

/**
 * Validation Plugin
 * @author ReGeDa
 */
class Validation extends Plugin_Object {

	/**
	 * Input data
	 * @var Input
	 */
	private $input;

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();
		$this->input = &platcode()->plugins->import('Input');
	}

	/**
	 * Get persistant plugin state
	 * @override
	 * @return boolean
	 */
	public function is_persistant() {
		return TRUE;
	}

	/**
	 * Parse input field
	 * @param string $field
	 * @return array
	 */
	private function field_name($field) {
		if (preg_match('/^((post|get|cookie):)?(.+)$/', $field, $matches)) {

			// set default on empty type
			if (empty($matches[2]))
				$matches[2] = 'post';

			// type/name
			return array($matches[2], $matches[3]);
		}
		throw new Platcode_Exception("Bad validation rule '$field' field");
	}

	/**
	 * Validate input by rules
	 * @param array $rules
	 * @param string $validator_class
	 * @param boolean $export_error
	 * @return boolean
	 */
	public function validate($rules, $validator_class, $export_error = TRUE) {

		$validator = &platcode()->plugins->import($validator_class);

		try {
			// GO!
			foreach ($rules as $field => $rule_raw) {

				list($type, $name) = $this->field_name($field);

				// get field value
				$value = &$this->input->$type($name);

				// field rules
				// "required" must be a first rule for required field
				// A value trimmed when rule "required" is present
				$rules = preg_split('/[\s]+:[\s]+/', $rule_raw, -1, PREG_SPLIT_NO_EMPTY);

				// verify a required field
				if ($rules[0] == 'required') {

					// strip whitespace
					$value = trim($value);

					if ($validator->check($field, 'required', $value))
						array_shift($rules);
					else
						throw new Exception(); // error
				}
				else if (is_null($value))
					// process a next field
					continue;


				// rules lookup
				foreach ($rules as $rule_name) {
					if ( ! $validator->check($field, $rule_name, $value))
						throw new Exception(); // error
				}
			}
			////////////////////// END
		} catch (Exception $e) {
			// output error
			if ($export_error)
				platcode()->raw['err'] = $validator->get_last_error();
			// for error
			return FALSE;
		}

		// success
		return TRUE;
	}
	
}

// end of file